package com.itheima.rpc.client.cluster;

import com.itheima.rpc.annotation.HrpcLoadBalance;
import com.itheima.rpc.client.config.RpcClientConfiguration;
import com.itheima.rpc.spring.SpringBeanFactory;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * @desc
 *
 * @author:ivan.liu
 *
 */
@Component
public class DefaultStartegyProvider implements StartegyProvider, ApplicationContextAware {

    @Autowired
    private RpcClientConfiguration configuration;

    private LoadBalanceStrategy loadBalanceStrategy;

    @Override
    public LoadBalanceStrategy getStrategy() {
        return loadBalanceStrategy;
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        Map<String, Object> objectMap = applicationContext.getBeansWithAnnotation(HrpcLoadBalance.class);
        for (Object value : objectMap.values()) {
            HrpcLoadBalance hrpcLoadBalance = value.getClass().getAnnotation(HrpcLoadBalance.class);
            String strategy = configuration.getRpcClientClusterStrategy();
            if(strategy.equals(hrpcLoadBalance.strategy())){
                this.loadBalanceStrategy= (LoadBalanceStrategy) value;
                break;
            }
        }
    }
}
